package cn.gzmli.dtt.common.service;

import cn.gzmli.dtt.common.dao.MenuDao;
import cn.gzmli.dtt.common.entity.Menu;
import cn.gzmli.dtt.common.entity.Role;
import cn.gzmli.dtt.common.entity.User;
import cn.gzmli.dtt.common.utils.BaseService;
import cn.gzmli.dtt.sbzyc.exception.SystemException;
import com.xiaoleilu.hutool.util.StrUtil;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Descript
 * @Author xsx
 * @Date 2017/12/25
 */
@Service
@Transactional
public class MenuService extends BaseService<Menu> {

    @Autowired
    private MenuDao menuDao;

    @Override
    public Menu save(Menu menu) throws Exception {
        Menu parent = this.get(menu.getParent().getId());
        if (parent==null){
            throw new SystemException("该菜单父节点不存在");
        }
        Map<String, String> condition = new HashMap<>();
        condition.put("name", "="+ StrUtil.wrap(menu.getName(), "'", "'"));
        Menu mu = this.getByCondition(condition);
        if (mu==null){
            menu.setId((Integer) this.getDao().insert(menu));
            //为管理员添加菜单
            final String sql = "INSERT INTO role_menu(roleId, menuId) VALUES(?,?)";
            this.getDao().getJdbcTemplate().update(sql, 1, menu.getId());

            final String update = "UPDATE menu SET isParent=1 WHERE id=?";
            this.getDao().getJdbcTemplate().update(update, menu.getParent().getId());
        }else{
            throw new SystemException("此菜单名称已存在");
        }
        return menu;
    }

    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private SessionFactory sessionFactory;
  /*  @Autowired
    private MenuRepository menuRepository;*/

    @Transactional(rollbackFor=Exception.class)
    public void updateMenu(Menu menu) throws Exception {
//        super.update(menu);
//       /* DefaultTransactionDefinition df=new DefaultTransactionDefinition();
//        TransactionStatus ts =transactionManager.getTransaction(df);*/
            menuDao.update(menu);
            /*menu.setId(null);
            Menu menux = new Menu();
            menux.setIsParent(0);
            menux.setName("哈哈");
            menux.setUrl(null);
            menux.setOrderNo(1);
            menux.setpId(1);
            menuDao.insert(menux);
//            menuRepository.save(menux);
            int x = Integer.parseInt("1xx");*/
//            transactionManager.commit(ts);


    }

    @Override
    public void delete(Menu menu) throws Exception {
        final String sql = "DELETE FROM role_menu WHERE menuId=?";
        this.getDao().getJdbcTemplate().update(sql, menu.getId());
        super.delete(menu);
    }

    public List<Menu> getUserMenuByPid(User user, Integer pId) throws Exception {
//        List<Object> params =  new ArrayList<>();
//        params.addAll(Arrays.asList(Convert.toIntArray(user.getRoleIds().split(","))));
//        StringBuilder sql = new StringBuilder();
//        sql.append("SELECT m.* FROM menu m ")
//            .append("INNER JOIN role_menu rm ON rm.menuId=m.id ")
//            .append("INNER JOIN role r ON r.id=rm.roleId ")
//            .append("WHERE r.id IN(").append(BaseUtil.getPlaceholder(params.size())).append(") ");
//        if (pId!=null){
//            sql.append("AND m.pid=?");
//            params.add(pId);
//        }
//        sql.append(" ORDER BY m.orderNo ASC ");
//        return this.getDao().getJdbcTemplate().queryForList(sql.toString(), params.toArray());
        Set<Role> roles = user.getRoles();
        Set<Menu> data = new HashSet<>();
        for (Role role : roles){
            for (Menu menu : role.getMenus()){
                if (menu.getParent()!=null&&menu.getParent().getId().intValue()==pId.intValue()){
                    data.add(menu);
                }
            }
        }
        List<Menu> dataList = new ArrayList<>(data);
        Collections.sort(dataList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return o1.getOrderNo()-o2.getOrderNo();
            }
        });

        return dataList;
    }

    public List<Map<String, Object>> getRoleAllMenus() throws Exception{
        final String sql = "SELECT * FROM menu ORDER BY id";
        return this.getDao().getJdbcTemplate().queryForList(sql);
    }
    
    /**
     * 根据菜单ID获取菜单信息
     * @param id
     * @return
     * @throws Exception
     * 20180402
     */
    public Menu queryMenuByID(String id) throws Exception{
    	
    	Map<String,String> condition=new HashMap<String, String>();
    	condition.put("id","="+id);
       return (Menu) this.getDao().queryOnlyEntity(condition);
       
    }
    
    /**
     * 根据菜单ID当前用户缓存中获取菜单信息
     * @param user
     * @param id
     * @return
     * @throws Exception
     */
    public Menu getMenuByID(User user,String id)throws Exception{
    	  Set<Role> roles = user.getRoles();
          Set<Menu> data = new HashSet<>();
          Menu menu=null;
          for (Role role : roles){
              for (Menu m : role.getMenus()){
                  if (m.getId().toString().equals(id)){
                    menu=m;
                    break;
                  }
              }
          }
          return menu;
    }

    public List<Map<String, Object>> getTabMenuById(Integer menuId) throws Exception {
        String sql = "SELECT m.* FROM menu m WHERE m.pId = " + menuId + " ORDER BY m.orderNo ASC ";
        return this.getDao().getJdbcTemplate().queryForList(sql);
    }
}
